<template>
  <div>
    <a-drawer
      v-model:visible="visible"
      class="custom-class"
      :title="title"
      placement="right"
      @close="modalClose.close"
      @after-visible-change="afterVisibleChange"
    >
      <div>
        <a-form :label-col="{ span: 8 }" :wrapper-col="{ span: 24 }" label-align="left" :layout="'vertical'">
          <a-form-item label="名称" v-bind="validateInfos.name">
            <a-input v-model:value="modelRef.name" :disabled="isDetl" placeholder="输入名称" />
          </a-form-item>
          <a-form-item label="图标" v-bind="validateInfos.icon">
            <a-input v-model:value="modelRef.icon" :disabled="isDetl" placeholder="" />
          </a-form-item>
          <a-form-item label="描述" v-bind="validateInfos.description">
            <a-textarea
              v-model:value="modelRef.description"
              placeholder="输入描述"
              :disabled="isDetl"
              :auto-size="{ minRows: 2, maxRows: 2 }"
            />
          </a-form-item>
        </a-form>
      </div>
      <div style="display: flex; justify-content: left">
        <div v-show="!isDetl">
          <a-button type="primary" @click="handleOk">{{ isDetl ? '关闭' : '确定' }}</a-button>
        </div>
        <div style="margin-left: 10px">
          <a-button @click="cancal">{{ isDetl ? '关闭' : '取消' }}</a-button>
        </div>
      </div>
      <a-modal v-model:visible="modalClose.modalVisible" title="关闭" @ok="modalClose.modalHandleOk">
        <span>数据未保存,确认关闭吗?</span>
      </a-modal>
    </a-drawer>
  </div>
</template>
<script>
import { defineComponent, toRaw, ref, watch, defineEmits, toRefs, onMounted, reactive, nextTick } from 'vue'
import { Form } from 'ant-design-vue'
const useForm = Form.useForm
import { message } from 'ant-design-vue'
import pack from '/package.json'
import factory from '../factory'
import html2canvas from 'html2canvas'
import exp from '@/utils/regular'
export default defineComponent({
  props: {
    isShowEdit: { type: Boolean, default: false },
    isEdit: { type: Number, default: 0 },
    currentItemC: {
      type: Object,
      default: () => {
        return {}
      },
    },
    isDetl: { type: Boolean, default: false },
  },
  emits: ['closeEdit', 'deletSuccess', 'editSuccess', 'createSuccess', 'updateSuccess'],
  setup(props, ctx) {
    const { isShowEdit, isEdit, currentItemC: currentItem, isDetl } = toRefs(props)

    /****表单===================*/
    const modelRef = reactive({
      name: '',
      description: '',
      icon: '',
    })
    const rulesRef = reactive({
      name: [
        {
          required: true,
          message: '请输入名称',
        },
        {
          pattern: exp.name.pattern,
          message: exp.name.message,
        },
        {
          max: 25,
          message: '最多输入25个字符',
        },
      ],
      description: [
        {
          required: false,
          message: '请输入描述',
        },
        {
          max: 127,
          message: '最多输入127个字符',
        },
      ],
      icon: [
        {
          required: false,
          message: '',
        },
      ],
    })
    const { validate, validateInfos } = useForm(modelRef, rulesRef, {
      //表单验证的输出: 字段 值 提示
      onValidate: (...args) => {
        console.log('表单验证的输出: 字段 值 提示', ...args)
        if (args.length && args[0] === 'html' && args[1]) {
          click_zhuanyuansu()
        } else {
          zt.value = null
        }
      },
    })
    const onSubmit = () => {
      validate()
        .then(() => {
          //表单验证无误后执行
          //==元素转base64图片
          let element = document.getElementById('lulantu')
          nextTick(() => {
            html2canvas(element).then((res) => {
              let img64 = res.toDataURL('image/jpeg')
              console.log('base64数据', img64)
            })
          })
          if (isEdit.value === 0) {
            //新增
            let post = modelRef
            factory.saveLayoutList(post).then((res) => {
              visible.value = false
              ctx.emit('createSuccess', modelRef.value)
              ctx.emit('closeEdit', false)
            })
          } else {
            //编辑
            let post = {
              html: modelRef.html,
              name: modelRef.name,
              id: modelRef.id,
              resourcePath: new Date() + '',
            }
            factory.updateLayoutList(post).then((res) => {
              visible.value = false
              ctx.emit('updateSuccess', modelRef)
              ctx.emit('closeEdit', false)
            })
          }
        })
        .catch((err) => {
          console.log('error', err)
        })
    }

    //== 主体程序 =================================
    const visible = ref(false)
    const handleOk = (e) => {
      onSubmit()
    }
    const cancal = () => {
      modalClose.close()
    }
    watch(visible, (newValue, oldValue) => {
      if (!newValue) {
        ctx.emit('closeEdit', false)
        let obj = toRaw(modelRef)
        obj.name = ''
        obj.description = ''
        obj.html = ''
        obj.label = ''
      }
    })
    const title = ref('')
    watch(isShowEdit, (newValue, oldValue) => {
      if (newValue) {
        let obj2 = currentItem.value
        if (isEdit.value === 1) {
          for (let key in obj2) {
            modelRef[key] = obj2[key]
          }
        }
        zt.value = null
        visible.value = true
        switch (isEdit.value) {
          case 0:
            title.value = '新增'
            break
          case 1:
            title.value = '编辑'
            break
        }
        if (isDetl.value) {
          title.value = '详情'
        }
        //备份数据
        modalClose.backupData = JSON.stringify(modelRef)
      }
    })

    //===转代码转网页元素================
    const zt = ref(null)
    const click_zhuanyuansu = () => {
      zt.value = regCom(modelRef.html)
      setTimeout(() => {
        suofang()
      }, 10)
    }
    //==缩放===========
    function suofang() {
      let block = document.getElementById('lulantu')
      Array.prototype.forEach.call(block.children, function (el) {
        // 宽度缩放比例:wr = el.offsetWidth/300, 高度缩放比例:hr = el.offsetHeight/200 , 取最大比例缩放
        let wr = el.offsetWidth / 300
        let r = wr
        el.style.transform = `scale(${1 / r},${1 / r})`
        el.style['transform-origin'] = '0% 0%'
      })
    }
    //==确认关闭对话框======================
    const modalClose = reactive({
      backupData: '',
      close: (e) => {
        if (JSON.stringify(modelRef) !== modalClose.backupData) {
          visible.value = true
          modalClose.modalVisible = true
          return
        }
        visible.value = false
      },
      modalVisible: false,
      modalHandleOk: () => {
        visible.value = false
      },
    })
    return {
      visible,
      handleOk,
      title,
      cancal,
      validateInfos,
      modelRef,
      zt,
      modalClose,
    }
  },
})
</script>
<style scoped>
#lulantu {
  width: 300px;
  height: 200px;
  overflow: hidden;
  border: 1px solid #d9d9d9;
}
</style>
